<?php
require_once("db/config.php");
header("Content-Type:text/html;charset=utf-8");
session_start();
if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    // 在数据库user表中查找$username
    $sql="select * from user where usr='$username'";
    $set=mysqli_query($con, $sql);
    $row = mysqli_fetch_array($set);
    // $flag= mysqli_num_rows($set);
    if (($username=='')||($password=='')) {
        header('refresh:3;url=login.php');
        echo "改用户名或密码不能为空，3秒后跳转到登录页面";
        exit;
    } elseif (($username!=$row['usr'])||($password!=$row['pwd'])) {
        //用户名或密码错误
        header('refresh:3;url=login.php');
        echo "用户名或密码错误，3秒后跳转到登录页面";
        exit;
    } elseif (($username==$row['usr'])&&($password==$row['pwd'])) {
        //登录成功将信息保存到session中
        $_SESSION['username']=$username;
        $_SESSION['islogin']=1;

        $sql = "delete from message where user='$username'";
        $result=mysqli_query($con, $sql);//执行语句
        // if ($result==1) {
        //     echo "<script>alert('删除成功!');</script>";
        // } else {
        //     echo "<script>alert('删除失败!');</script>";
        // }
        // 写数据库
        $usr = $username;
        $sid = session_id();
        $time=date("Y-m-d G:i:s");//获取时间，G为24小时制
        $sql="insert into message(user,sid,time) values('$usr','$sid','$time')";
        $result=mysqli_query($con, $sql);//执行语句
        // if ($result==1) {
        //     echo "<script>alert('写入数据库成功');</script>";
        // } else {
        //     echo "<script>alert('写入数据库失败');</script>";
        // }

        //如果勾选7天内自动保存，则将其保存到cookie
        if ($_POST['remember']=="yes") {
            setcookie("username", $username, time()+7*24*60*60);
            setcookie("code", md5($username.md5($password)), time()+7*24*60*60);
        } else {
            setcookie("username", '', time()-1);
            setcookie("code", '', time()-1);
        }
        //跳转到用户首页
        header('refresh:3;url=index.php');
    }
}
